package ntd.task;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import ntd.task.bo.TaskInfo;
import ntd.util.UtilRun;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TaskManager {

    private static final Map<String, TaskInfo> TASK_INFO_MAP = new HashMap<>();

    public static void register(TaskInfo taskInfo) throws Exception {
        if (ObjectUtil.isNotNull(taskInfo)) {
            if (TASK_INFO_MAP.containsKey(taskInfo.getTaskCode())) {
                throw new Exception("任务code重复，请检查代码！");
            }
            TASK_INFO_MAP.put(taskInfo.getTaskCode(), taskInfo);
        }
    }

    public static TaskInfo get(String task) {
        init();
        return TASK_INFO_MAP.get(task);
    }

    public static List<TaskInfo> list() {
        init();
        return ListUtil.toList(TASK_INFO_MAP.values());
    }

    public static void init() {
        UtilRun.onlyOne("ntd.task.TaskManager.init", () -> {
            Set<Class<?>> classes = ClassUtil.scanPackageBySuper("ntd", Task.class);
            for (Class<?> aClass : classes) {
                Task task = (Task) ReflectUtil.newInstance(aClass);
                register(task.info());
            }
        });
    }

}
